<template>
  <div class="system-role">
    <!-- 搜索筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="角色名称">
          <el-input 
            v-model="searchForm.name" 
            placeholder="请输入角色名称" 
            clearable 
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="角色编码">
          <el-input 
            v-model="searchForm.code" 
            placeholder="请输入角色编码" 
            clearable 
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <el-button type="primary" @click="handleCreate">
          <el-icon><Plus /></el-icon>
          新建角色
        </el-button>
        <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedRows.length">
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
      </div>
    </div>

    <!-- 角色列表 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="角色名称" width="150" />
        <el-table-column prop="code" label="角色编码" width="150" />
        <el-table-column prop="description" label="角色描述" min-width="200" />
        <el-table-column prop="userCount" label="用户数量" width="100" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="150" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="text" size="small" @click="handleAssignPermission(row)">
              分配权限
            </el-button>
            <el-popconfirm title="确定删除该角色吗？" @confirm="handleDelete(row)">
              <template #reference>
                <el-button type="text" size="small" style="color: #f56c6c;">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="loadTableData"
          @size-change="loadTableData"
        />
      </div>
    </el-card>

    <!-- 角色表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'create' ? '新建角色' : '编辑角色'"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="80px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="formData.code" placeholder="请输入角色编码" :disabled="dialogType === 'edit'" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="formData.description" type="textarea" :rows="3" placeholder="请输入角色描述" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 权限分配对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="分配权限"
      width="800px"
      :close-on-click-modal="false"
    >
      <div class="permission-header">
        <h4>为角色 "{{ currentRole.name }}" 分配权限</h4>
        <div class="permission-actions">
          <el-button size="small" @click="handleExpandAll">
            {{ expandAll ? '收起' : '展开' }}全部
          </el-button>
          <el-button size="small" @click="handleCheckAll">
            {{ checkAll ? '取消' : '全选' }}
          </el-button>
        </div>
      </div>
      
      <el-tree
        ref="permissionTreeRef"
        :data="permissionTree"
        show-checkbox
        node-key="id"
        :default-expand-all="false"
        :check-strictly="false"
        :props="{ label: 'name', children: 'children' }"
        class="permission-tree"
      >
        <template #default="{ node, data }">
          <div class="permission-node">
            <el-icon v-if="data.type === 'menu'"><Menu /></el-icon>
            <el-icon v-else-if="data.type === 'button'"><Operation /></el-icon>
            <span>{{ data.name }}</span>
            <el-tag v-if="data.code" size="small" type="info">{{ data.code }}</el-tag>
          </div>
        </template>
      </el-tree>
      
      <template #footer>
        <el-button @click="permissionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSavePermissions" :loading="permissionLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Delete, Menu, Operation } from '@element-plus/icons-vue'
import { getRoles, createRole, updateRole, deleteRole, getPermissions, getRolePermissions, updateRolePermissions } from '@/api/admin'

export default {
  name: 'SystemRole',
  components: {
    Search, Refresh, Plus, Delete, Menu, Operation
  },
  setup() {
    const loading = ref(false)
    const submitLoading = ref(false)
    const permissionLoading = ref(false)
    const dialogVisible = ref(false)
    const permissionDialogVisible = ref(false)
    const dialogType = ref('create')
    const selectedRows = ref([])
    const formRef = ref()
    const permissionTreeRef = ref()
    const expandAll = ref(false)
    const checkAll = ref(false)

    const searchForm = reactive({
      name: '',
      code: '',
      status: ''
    })

    const pagination = reactive({
      current: 1,
      size: 10,
      total: 0
    })

    const tableData = ref([])
    const currentRole = ref({})
    const permissionTree = ref([])

    const formData = reactive({
      id: '',
      name: '',
      code: '',
      description: '',
      status: 1,
      remark: ''
    })

    const formRules = {
      name: [
        { required: true, message: '请输入角色名称', trigger: 'blur' },
        { min: 2, max: 20, message: '角色名称长度在 2 到 20 个字符', trigger: 'blur' }
      ],
      code: [
        { required: true, message: '请输入角色编码', trigger: 'blur' },
        { pattern: /^[A-Z_]+$/, message: '角色编码只能包含大写字母和下划线', trigger: 'blur' }
      ],
      description: [
        { required: true, message: '请输入角色描述', trigger: 'blur' }
      ]
    }

    // 加载表格数据
    const loadTableData = async () => {
      loading.value = true
      try {
        const res = await getRolesList({
          page: pagination.current,
          size: pagination.size,
          ...searchForm
        })
        
        if (res.code === 200) {
          tableData.value = res.data.records || []
          pagination.total = res.data.total || 0
        }
      } catch (error) {
        console.error('获取角色列表失败:', error)
        ElMessage.error('获取角色列表失败')
      } finally {
        loading.value = false
      }
    }

    // 加载权限树
    const loadPermissionTree = async () => {
      try {
        const res = await getPermissionsList()
        if (res.code === 200) {
          permissionTree.value = res.data || []
        }
      } catch (error) {
        console.error('加载权限树失败:', error)
        ElMessage.error('加载权限树失败')
      }
    }

    // 搜索
    const handleSearch = () => {
      pagination.current = 1
      loadTableData()
    }

    // 重置
    const handleReset = () => {
      Object.assign(searchForm, {
        name: '',
        code: '',
        status: ''
      })
      handleSearch()
    }

    // 新建
    const handleCreate = () => {
      dialogType.value = 'create'
      dialogVisible.value = true
      resetFormData()
    }

    // 编辑
    const handleEdit = (row) => {
      dialogType.value = 'edit'
      dialogVisible.value = true
      Object.assign(formData, row)
    }

    // 删除
    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm('确定要删除该角色吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const res = await deleteRole(row.id)
        if (res.code === 200) {
          ElMessage.success('删除成功')
          loadTableData()
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }

    // 批量删除
    const handleBatchDelete = async () => {
      if (!selectedRows.value.length) return
      
      try {
        await ElMessageBox.confirm('确定删除选中的角色吗？', '提示', {
          type: 'warning'
        })
        
        const ids = selectedRows.value.map(row => row.id)
        const res = await deleteRole(ids)
        if (res.code === 200) {
          ElMessage.success('批量删除成功')
          loadTableData()
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }

    // 状态变更
    const handleStatusChange = async (row) => {
      try {
        const res = await updateRole(row.id, { status: row.status })
        if (res.code === 200) {
          ElMessage.success(`${row.status ? '启用' : '禁用'}成功`)
        }
      } catch (error) {
        row.status = !row.status
        ElMessage.error('操作失败')
      }
    }

    // 分配权限
    const handleAssignPermission = async (row) => {
      currentRole.value = row
      permissionLoading.value = true
      
      try {
        // 获取所有权限
        const permRes = await getPermissionsList()
        if (permRes.code === 200) {
          permissionTree.value = permRes.data || []
        }
        
        // 获取角色权限
        const rolePermRes = await getRolePermissions(row.id)
        if (rolePermRes.code === 200) {
          selectedPermissions.value = rolePermRes.data || []
        }
        
        permissionDialogVisible.value = true
      } catch (error) {
        ElMessage.error('获取权限数据失败')
      } finally {
        permissionLoading.value = false
      }
    }

    // 展开/收起所有节点
    const handleExpandAll = () => {
      expandAll.value = !expandAll.value
      const nodes = permissionTreeRef.value.store._getAllNodes()
      nodes.forEach(node => {
        node.expanded = expandAll.value
      })
    }

    // 全选/取消全选
    const handleCheckAll = () => {
      checkAll.value = !checkAll.value
      if (checkAll.value) {
        const allKeys = getAllNodeKeys(permissionTree.value)
        permissionTreeRef.value.setCheckedKeys(allKeys)
      } else {
        permissionTreeRef.value.setCheckedKeys([])
      }
    }

    // 获取所有节点key
    const getAllNodeKeys = (nodes) => {
      const keys = []
      const traverse = (nodeList) => {
        nodeList.forEach(node => {
          keys.push(node.id)
          if (node.children && node.children.length) {
            traverse(node.children)
          }
        })
      }
      traverse(nodes)
      return keys
    }

    // 保存权限分配
    const handleSavePermissions = async () => {
      try {
        const checkedKeys = permissionTreeRef.value.getCheckedKeys()
        const halfCheckedKeys = permissionTreeRef.value.getHalfCheckedKeys()
        const allKeys = [...checkedKeys, ...halfCheckedKeys]
        
        const res = await updateRolePermissions(currentRole.value.id, allKeys)
        if (res.code === 200) {
          ElMessage.success('权限分配成功')
          permissionDialogVisible.value = false
          loadTableData()
        }
      } catch (error) {
        ElMessage.error('权限分配失败')
      }
    }

    // 选择变更
    const handleSelectionChange = (selection) => {
      selectedRows.value = selection
    }

    // 提交表单
    const handleSubmit = async () => {
      if (!formRef.value) return
      
      try {
        await formRef.value.validate()
        submitLoading.value = true
        
        let res
        if (dialogType.value === 'create') {
          res = await createRole(formData)
        } else {
          res = await updateRole(formData.id, formData)
        }
        
        if (res.code === 200) {
          ElMessage.success(dialogType.value === 'create' ? '创建成功' : '更新成功')
          dialogVisible.value = false
          loadTableData()
        }
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('操作失败')
      } finally {
        submitLoading.value = false
      }
    }

    // 重置表单
    const resetFormData = () => {
      Object.assign(formData, {
        id: '',
        name: '',
        code: '',
        description: '',
        status: 1,
        remark: ''
      })
    }

    onMounted(() => {
      loadTableData()
      loadPermissionTree()
    })

    return {
      loading,
      submitLoading,
      permissionLoading,
      dialogVisible,
      permissionDialogVisible,
      dialogType,
      selectedRows,
      formRef,
      permissionTreeRef,
      expandAll,
      checkAll,
      searchForm,
      pagination,
      tableData,
      currentRole,
      permissionTree,
      formData,
      formRules,
      loadTableData,
      handleSearch,
      handleReset,
      handleCreate,
      handleEdit,
      handleDelete,
      handleBatchDelete,
      handleStatusChange,
      handleAssignPermission,
      handleExpandAll,
      handleCheckAll,
      handleSavePermissions,
      handleSelectionChange,
      handleSubmit
    }
  }
}
</script>

<style scoped>
.system-role {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.permission-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.permission-header h4 {
  margin: 0;
  color: #303133;
}

.permission-actions {
  display: flex;
  gap: 10px;
}

.permission-tree {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
}

.permission-node {
  display: flex;
  align-items: center;
  gap: 8px;
}

.permission-node .el-tag {
  margin-left: auto;
}
</style> 